import React, { useRef } from 'react'
import styles from './index.module.less'
import iconUpload from '@/resource/archives/icon_upload.png'
import { getData, postData, postFile, putData } from '@/servers/http'
import { api } from '@/servers/api'
import { observer } from 'mobx-react'
import store from '../../store'
import { SourceEnum } from '@/const'
import { getLocalStorage, setLocalStorage } from '@/storage'
import { Dialog, Toast } from 'antd-mobile'
import dayjs from 'dayjs'
import wx from 'weixin-webview-jssdk'

const UploadPhoto = () => {
    const identityType = getLocalStorage('IDENTITY_TYPE')
    const { fileDetail, getFileDetail } = store || {}
    const camera = useRef<any>(null)
    /** 档案提交 */
    const submitArchive = async (data: { url: any; name: string; sort: number }[]) => {
        let res
        const params = {
            fill_type: 2,
            data,
        }
        if (fileDetail.is_finished !== '1') {
            res = await postData(`${api.userBarriersBatchInput}${fileDetail.id}`, params)

            if (Number(identityType) !== 2 && res.data?.gain_medal) {
                wx.miniProgram.navigateTo({
                    url: `/pageStudent/pages/gotMedal/index?medalData=${encodeURIComponent(JSON.stringify(res.data.gain_medal))}`,
                })
            }
        } else {
            res = await putData(`${api.userBarriersBatchUpdate}${fileDetail.id}`, params)
        }
        if (res.status === 200) {
            getFileDetail()
        }
    }
    /** 批量上传照片 */
    const batchUploadPhotos = (files: any[]) => {
        if (files?.length > 0) {
            const promiseArr: any[] = []
            files.forEach((file: File) => {
                const fileName = dayjs().valueOf() + file.name.substring(file.name.lastIndexOf('.'))
                const newFile = new File([file], fileName, { type: file.type })
                promiseArr.push(postFile(api.uploads, { file: newFile, type: 'barrier_img' }))
            })
            const toast = Toast.show({
                icon: 'loading',
                content: '上传中…',
                duration: 0,
            })
            Promise.allSettled(promiseArr)
                .then(res => {
                    const fileData: { url: any; name: string; sort: number }[] = []
                    let sort = 1
                    res.forEach(item => {
                        if (item.status === 'fulfilled') {
                            const { ext, name, url } = item.value.data || {}
                            fileData.push({ url, name: name + '.' + ext, sort: sort++ })
                        }
                    })
                    submitArchive(fileData)
                    toast.close()
                })
                .catch(() => {
                    toast.close()
                })
        }
    }
    /** 上传照片 */
    const upLoadImage = (e: any) => {
        if (Number(identityType) === 2) {
            batchUploadPhotos(e.target?.files)
        } else {
            getData(api.userBarriersScoreInfo).then(({ data }) => {
                if (Number(data?.is_score) === 1) {
                    Toast.show(Number(data?.is_course_score) === 1 ? '讲师已评分' : '讲师已评审')
                    return
                } else {
                    batchUploadPhotos(e.target?.files)
                }
            })
        }
    }
    /** 打开相册 */
    const openPhotoAlbum = () => {
        setLocalStorage('ARCHIVE_DETAIL_SOURCE', SourceEnum.UPLOAD_PHOTO)
        if (fileDetail.is_finished === '1') {
            Dialog.confirm({
                content: '档案已完成，是否要重新编辑',
                confirmText: '继续',
                onConfirm: () => {
                    camera.current?.click()
                },
            })
        } else {
            camera.current?.click()
        }
    }

    return (
        <>
            <div className={styles.header_btn} onClick={openPhotoAlbum}>
                <img src={iconUpload} />
                <span>上传照片</span>
            </div>
            <input ref={camera} type="file" accept="image/*" multiple onChange={upLoadImage} style={{ display: 'none', cursor: 'pointer' }} />
        </>
    )
}

export default observer(UploadPhoto)
